package cn.qu.v1.platform.plugin.loader;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;

/**
 * Created by zh on 17/1/7.
 */
public class PluginLoader extends URLClassLoader {
    private PluginLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    private PluginLoader(URL[] urls) {
        super(urls);
    }

    private PluginLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
        super(urls, parent, factory);
    }

    public static URL toJarURL(String file) throws MalformedURLException {
        return new URL("jar", "", String.format("file:%s!/", file));
    }

    public static PluginLoader create(String[] pluginPaths, ClassLoader classLoader) {
        ArrayList<URL> url = new ArrayList<>();
        for (String pluginPath : pluginPaths) {
            if (pluginPath.endsWith(".jar")) {
                try {
                    url.add(toJarURL(pluginPath));
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }
        if (classLoader != null) {
            return new PluginLoader(url.toArray(new URL[0]), classLoader);
        } else {
            return new PluginLoader(url.toArray(new URL[0]));
        }
    }

    public static PluginLoader create(String[] pluginPaths) {
        return create(pluginPaths, null);
    }
}
